package cn.meomis.action;

import java.awt.Color;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import cn.meomis.common.entity.Pagination;
import cn.meomis.common.util.Constant;
import cn.meomis.common.util.DataTableParam;
import cn.meomis.model.Che;
import cn.meomis.model.SysLog;
import cn.meomis.model.Value;
import cn.meomis.model.ValueDetail;
import cn.meomis.service.CheService;
import cn.meomis.service.SysLogService;
import cn.meomis.service.ValueDetailService;
import cn.meomis.service.ValueService;

//@Scope("prototype") 
@Controller
//@Namespace("/")
@ParentPackage("json-default")
//@Result(name="success", type="json")
public class CheAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private Che che;
	
	/**
	 * 没有备份的数据报表
	 */
	private String notbackupsfileName;		
	
	/**
	 * 已经备份过得数据报表
	 */
	private String isbackupsfileName;
	
	// @Resource
	@Autowired
	private CheService cheService;
	
	@Autowired
	private ValueService valueService;
	
	@Autowired
	private ValueDetailService valueDetailService;
	
	@Autowired
	private SysLogService sysLogService;		//日志

	
	@Action(value = "/cheAction", results = { @Result(name = SUCCESS, location = "/manager/modules/che/che.jsp")})
	@Override
	public String execute() {
/*		String type = httpServletRequest.getParameter("type");
		List<Demo> demoList = valueService.findAll();
		httpServletRequest.setAttribute("DEMO_LIST", demoList);
		if ("manager".equals(type)) {
			return "manager";
		}*/
		return SUCCESS;
	}
/*	@Action(value = "/valueAction", results = { @Result(name = SUCCESS, location = "/manager/modules/demo/index.jsp"),
												@Result(name = "manager", location = "/manager/modules/demo/notice.jsp")})
	@Override
	public String execute() {
		String type = httpServletRequest.getParameter("type");
		List<Demo> demoList = valueService.findAll();
		httpServletRequest.setAttribute("DEMO_LIST", demoList);
		if("manager".equals(type)){
			return "manager";
		}
		return SUCCESS;
	}*/
	
	@Action(value = "/findCheAction", results = { @Result(name = SUCCESS, location = "/manager/modules/che/edit.jsp") })
	public String find(){
		Che che = cheService.findById(Integer.parseInt(httpServletRequest.getParameter("id")));
		httpServletRequest.setAttribute("CHE", che);
		return SUCCESS;
	}

	@Action(value = "/cheEditAction", results = { @Result(name = SUCCESS, location = "/cheAction.action", type = "redirect") })
	public String cheEdit() throws UnsupportedEncodingException {
		Che cheInstance = cheService.findById(che.getId());
		cheInstance.setCreatetime(new Date());
//		cheInstance.setName(che.getName());
//		cheInstance.setDes(che.getDes());
		cheInstance.setName(new String(che.getName().getBytes("ISO-8859-1"),"utf-8"));
		cheInstance.setDes(new String(che.getDes().getBytes("ISO-8859-1"),"utf-8"));
//		user.setUserid(new String(httpServletRequest.getParameter("userid").getBytes("ISO-8859-1"),"utf-8"));
		
		try {
			SysLog sl = new SysLog();
			sl.setContent("修改车类型,修改前名称["+cheInstance.getName()+"],修改后名称["+che.getName()+"]");
			sl.setCreateDate(new Date());
			sysLogService.save(sl);
		} catch (Exception e) {

			e.printStackTrace();
		}
		
		cheService.save(cheInstance);
		return SUCCESS;
	}
	
	
/*	@Action(value = "/userEditAction", results = { @Result(name = SUCCESS, location = "/userAction.action", type = "redirect") })
	public String edit(){
		User user = new User();
		user.setId(Integer.parseInt(httpServletRequest.getParameter("id")));
//		user.setUsername(httpServletRequest.getParameter("username"));
//		user.setPassword(httpServletRequest.getParameter("password"));
//		user.setAge(Integer.parseInt(httpServletRequest.getParameter("age")));
		userService.save(user);
		return SUCCESS;
	}*/
	
	@Action(value="/cheAddAction",results=@Result(name="success", type="json"))
	public void addNotice(){
		String result = "success";
		
		che.setCreatetime(new Date());
		cheService.save(che);
		try {
			SysLog sl = new SysLog();
			sl.setContent("创建车类型,名字["+che.getName()+"]");
			sl.setCreateDate(new Date());
			sysLogService.save(sl);
		} catch (Exception e1) {
			e1.printStackTrace();
			result = "error";
		}
		
		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();	
		try {
			jsonResponse.put("isSorF", result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Action(value = "/cheDeleteAction", results = { @Result(name = SUCCESS, location = "/cheAction.action", type = "redirect") })
	public String delete() {
		int id = Integer.parseInt(httpServletRequest
				.getParameter("id"));
		try {
			SysLog sl = new SysLog();
			sl.setContent("删除车类型,名称["+cheService.findById(id).getName()+"]");
			sl.setCreateDate(new Date());
			sysLogService.save(sl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cheService.removeById(id);
		return SUCCESS;
	}
	
	
	@Action(value = "/cheDelete", results = @Result(name = "success", type = "json"))
	public void deleteDestination(){
		String reslut = "success";
		try {
			int id = Integer.parseInt(httpServletRequest
					.getParameter("id"));
			try {
				SysLog sl = new SysLog();
				sl.setContent("删除车类型,名称["+cheService.findById(id).getName()+"]");
				sl.setCreateDate(new Date());
				sysLogService.save(sl);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//删除车属性信息
			DetachedCriteria detachedCriteria_value = DetachedCriteria.forClass(Value.class);
			detachedCriteria_value.add(Restrictions.eq("cheId", id));
			List<Value> vaList = valueService.queryList(detachedCriteria_value);
			for(Value va : vaList){
				valueService.removeById(va.getId());
			}
			
			//删除车属性累加值信息
			DetachedCriteria detachedCriteria_valueDetail = DetachedCriteria.forClass(ValueDetail.class);
			detachedCriteria_valueDetail.add(Restrictions.eq("cheId", id));
			List<ValueDetail> valueDetailList = valueDetailService.queryList(detachedCriteria_valueDetail);
			for(ValueDetail vd : valueDetailList){
				valueDetailService.removeById(vd.getId());
			}
			
			//删除车类型信息
			cheService.removeById(id);
			
		} catch (Exception e1) {
			e1.printStackTrace();
			reslut = "failure";
		}

		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();	
		try {
			jsonResponse.put("isSorF", reslut);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
/*	@Action(value = "/demoLoginAction", results = { @Result(name = SUCCESS, location = "/demoAction.action?type=manager", type = "redirect" ),
													@Result(name = "login", location = "/login.jsp" )})
	public String login() {
		String username = httpServletRequest.getParameter("username");
		String password = httpServletRequest.getParameter("password");
		if("admin".equals(username) && "admin".equals(password)){
			return SUCCESS;
		}else{
			return "login";
		}
	}*/
	
	
	@SuppressWarnings({ "unchecked", "unused" })
	@Action(value="/cheListAction")
	public void listDestination() {

		DataTableParam params = null;
		try {
			params = getParam();
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		HashMap<String, String> paramMap = convertToMap(params.getVoList());	
		String sEcho = paramMap.get("sEcho");
		Long iTotalRecords; // total number of records (unfiltered)
		Long iTotalDisplayRecords; //value will be set when code filters companies by keyword
		JSONArray data = new JSONArray(); //data that will be shown in the table

		int pageNumber = (Integer.parseInt(paramMap.get("iDisplayStart")) / Integer.parseInt(paramMap.get("iDisplayLength"))) + 1;

		StringBuffer hql =new StringBuffer( "from Che demo ");
		if (params.getIsQuery().equalsIgnoreCase("true")) {
			hql.append(" where 1 = 1 ");
			String name = paramMap.get("name").trim();
			String des = paramMap.get("des").trim();
			if (!"".equalsIgnoreCase(name)) {
				hql.append(" and demo.name like '%"+name+"%' ");
			}
			
			if (!"".equalsIgnoreCase(des)) {
				hql.append(" and demo.des like '%"+des+"%' ");
			}
		}
		
		String sCol = paramMap.get("iSortCol_0");
		String sortingColName =  paramMap.get("mDataProp_"+sCol);
		//asc or desc
	    String sdir = paramMap.get("sSortDir_0");
	   
	    if("0".equals(sortingColName)){
//	    	sortingColName = "dest.destination";
	    }else if("1".equals(sortingColName)){
	    	sortingColName = "demo.name";
	    }else if("2".equals(sortingColName)){
	    	sortingColName = "demo.des";
	    }else if("3".equals(sortingColName)){
	    	sortingColName = "demo.createtime";
	    }
	    
    	if ("desc".equalsIgnoreCase(sdir)) {
	    	hql.append(" order by "+sortingColName +" desc");
	    }else{
	    	hql.append(" order by "+sortingColName );
	    }
	    

		Object[] values = null;
		Pagination pageMqDestination = cheService.pageQueryByHql(hql.toString(), values, hql.toString(), pageNumber, Integer.parseInt(paramMap.get("iDisplayLength")));
		iTotalRecords = pageMqDestination.getTotalCount();
		List<Che> companies = (List<Che>) pageMqDestination.getResult();
//		List<Value> companies = new LinkedList<Demo>();
//		for(Demo c : apps){
//			companies.add(c);
//		}
		
		iTotalDisplayRecords = pageMqDestination.getTotalCount();

	
		try {
			JSONObject jsonResponse = new JSONObject();			
			jsonResponse.put("sEcho", sEcho);
			jsonResponse.put("iTotalRecords", iTotalRecords);
			jsonResponse.put("iTotalDisplayRecords", iTotalDisplayRecords);
			int i = 1;
			for(Che c : companies){
				JSONArray row = new JSONArray();
				row.put(i++);
				row.put(c.getName());
				row.put(c.getDes());
				row.put(dateformat.format(c.getCreatetime()));
				row.put(c.getId());
				data.put(row);
			}
			jsonResponse.put("resultList", data);
			httpServletResponse.setContentType("application/Json;charset=utf-8");
			httpServletResponse.getWriter().print(jsonResponse.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
			httpServletResponse.setContentType("text/html");
			try {
				httpServletResponse.getWriter().print(e.getMessage());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	
	@Action(value = "/cheReportAction", results = { @Result(name = SUCCESS, location = "/manager/modules/report/meomisReport1.jsp")})
	public String cheReport() throws IOException {
		
		notBackupsReport();
		isBackupsReport();
		
		return SUCCESS;
	}

	//没有进行备份的报表方法
	private void notBackupsReport() throws IOException {

		CategoryDataset dataset = getDataSetByDB(Integer.parseInt(httpServletRequest
				.getParameter("id")),Constant.VALUEDETAILNOTBACKUPS);
		JFreeChart chart = ChartFactory.createBarChart3D("车辆阀门值统计图(当前未备份数据)", // 图表标题
				"累加值和阀门值", // 目录轴的显示标签
				"阀门值", // 数值轴的显示标签
				dataset, // 数据集
				PlotOrientation.VERTICAL, // 图表方向：水平、垂直
				true, // 是否显示图例(对于简单的柱状图必须是false)
				false, // 是否生成工具
				false // 是否生成URL链接
				);
		/* double[][] data  = {{1185,995,1286,1210},{916,1028,900,885},{982,763,935,665},{384,568,928,773}};
	        String[] rowKeys = {"A产品","B产品","C产品","D产品"};
	        String[] columKeys = {"E-1区","E-2区","E-3区","E-4区"};
	        //创建Dataset对象
	        CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columKeys, data);*/
	        //创建3D柱状图
//	        JFreeChart chart = ChartFactory.createBarChart3D("2011年产品销售量", "", "销量/件", dataset, PlotOrientation.VERTICAL, true, true, false);
	        //设置背景颜色
	        chart.setBackgroundPaint(Color.WHITE);
	        notbackupsfileName = ServletUtilities.saveChartAsPNG(chart, 700, 600, null, getHttpSession());
	}
	
	
	//备份后的报表方法
	private void isBackupsReport() throws IOException {
		CategoryDataset dataset = getDataSetByDB(Integer.parseInt(httpServletRequest
				.getParameter("id")),Constant.VALUEDETAILISBACKUPS);

		JFreeChart chart = ChartFactory.createBarChart3D("车辆阀门值统计图(备份数据)", // 图表标题
				"累加值和阀门值", // 目录轴的显示标签
				"阀门值", // 数值轴的显示标签
				dataset, // 数据集
				PlotOrientation.VERTICAL, // 图表方向：水平、垂直
				true, // 是否显示图例(对于简单的柱状图必须是false)
				false, // 是否生成工具
				false // 是否生成URL链接
				);
		/* double[][] data  = {{1185,995,1286,1210},{916,1028,900,885},{982,763,935,665},{384,568,928,773}};
	        String[] rowKeys = {"A产品","B产品","C产品","D产品"};
	        String[] columKeys = {"E-1区","E-2区","E-3区","E-4区"};
	        //创建Dataset对象
	        CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columKeys, data);*/
	        //创建3D柱状图
//	        JFreeChart chart = ChartFactory.createBarChart3D("2011年产品销售量", "", "销量/件", dataset, PlotOrientation.VERTICAL, true, true, false);
	        //设置背景颜色
	        chart.setBackgroundPaint(Color.WHITE);
	        isbackupsfileName = ServletUtilities.saveChartAsPNG(chart, 700, 600, null, getHttpSession());
	}
	
	//CategoryDataset
	private CategoryDataset getDataSetByDB(int cheId,int isOrNotBackup) {
		
		//车类型
		Che cheInstance = cheService.findById(cheId);
		
		
		//车类型下的属性
		DetachedCriteria detachedCriteriaValue = DetachedCriteria.forClass(Value.class);
		detachedCriteriaValue.add(Restrictions.eq("cheId", cheId));
		
		List<Value> listValues = valueService.queryList(detachedCriteriaValue);
		
		
		//车类型属性对应的累加值
		DetachedCriteria detachedCriteriaValueDetail = DetachedCriteria.forClass(ValueDetail.class);
		detachedCriteriaValueDetail.add(Restrictions.eq("cheId", cheId));
		detachedCriteriaValueDetail.add(Restrictions.eq("backupsState", isOrNotBackup));
		List<ValueDetail> listValueDetails = valueDetailService.queryList(detachedCriteriaValueDetail);
		int leiji = 0;		//累加值迭代总和
		for(ValueDetail vd : listValueDetails){
			leiji = leiji + vd.getValuedetail();
		}
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		
		for(Value val : listValues){
			dataset.addValue(val.getValue(), cheInstance.getName()+"阀门值", val.getTypename());
			
			dataset.addValue(leiji, "当前累加值", val.getTypename());
			
		}

		return dataset;
	}

	public Che getChe() {
		return che;
	}

	public void setChe(Che che) {
		this.che = che;
	}

	public String getNotbackupsfileName() {
		return notbackupsfileName;
	}

	public void setNotbackupsfileName(String notbackupsfileName) {
		this.notbackupsfileName = notbackupsfileName;
	}

	public String getIsbackupsfileName() {
		return isbackupsfileName;
	}

	public void setIsbackupsfileName(String isbackupsfileName) {
		this.isbackupsfileName = isbackupsfileName;
	}

/*	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}*/



}
